package com.hr.mes.controller;

import com.hr.mes.dto.Result;
import com.hr.mes.entity.User;
import com.hr.mes.enums.MyExceptionEnum;
import com.hr.mes.exception.MyException;
import com.hr.mes.service.UserService;
import com.hr.mes.utils.JWTUtil;
import com.hr.mes.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "登录")
@CrossOrigin
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录时校验用户名和密码，然后返回JWTToken，后续请求都会被JWTFilter拦截，并验证token
     * @param loginVO
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVO loginVO){
        try{
            User user = userService.getUserByEmployeeNumber(loginVO.getEmployeeNumber());
            if(ObjectUtils.isEmpty(user) || !user.getPassword().equals(loginVO.getPassword())){
                throw new MyException(MyExceptionEnum.LOGIN_ERROR, null);
            }

            String jwt = JWTUtil.generate(loginVO.getEmployeeNumber());
            return Result.ok(jwt);
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            throw new MyException(MyExceptionEnum.LOGIN_ERROR, e);
        }
    }

}
